 /**
 * @file rc_usart.cpp
 * @author LJY (2250017028@qq.com)
 * @brief 
 * @version 0.1
 * @date 2022-03-03
 * 
 * @copyright Copyright (c) 2022
 * 
 */
#include <common/Driver/drv_usart.h>


void Usart::getData(void* dst, uint16_t size){
    memcpy(dst, rev_buf, size);
}

void Usart::sendData(void* src, uint16_t size)
{
    // 串口打开再发送
    if(serial_port.isOpen())
    {
        try{
            serial_port.write((uint8_t*)src, size);
        }
        catch(std::exception& e){
            ROS_ERROR("Unable to write the serial port");
        }
    }
}

/**
 * @brief 需要先调用这个函数才可以正常使用串口
 * 
 */
void Usart::start(void){
    try
    {    
        serial_port.open();
    }
    catch(std::exception& e)
    {
        ROS_ERROR("Unable to open the serial port");
    }
    if(serial_port.isOpen()) ROS_INFO("Successfully open the serial port");
}

void Usart::stop(void){
    try
    {    
        serial_port.close();
    }
    catch(std::exception& e)
    {
        ROS_ERROR("Unable to close the serial port");
    }
    if(!serial_port.isOpen()) ROS_INFO("Successfully close the serial port");    
}
/**
 * @brief 更新数据，这个函数需要放在某个节点中不断运行才可以更新串口实时数据
 * 
 */
uint8_t Usart::updateData(void){
    if(serial_port.isOpen())
    {
        // 读取串口中有效数据个数
        size_t recv_size = serial_port.available();
        if(recv_size > 0)
        {
            // 读取串口数据
            try{
                recv_size = serial_port.read(rev_buf, recv_size);
             }
            catch(std::exception& e){
                ROS_ERROR("Unable to read the serial port");
            }
            
            return 0;
        }
        else return 1;
    }
    else return 1;
}

